import { User } from '../modal/index'; // 数据库实体类
import { statusList } from '../common/status'; // 数据库实体类

function checkPermission(Request, Response, permission) {
  return new Promise((resolve, reject) => {
    if (Request.signedCookies && Request.signedCookies.token) {
      let uid = JSON.parse(Request.signedCookies.token).uid
      let timeStamp = JSON.parse(Request.signedCookies.token).timeStamp
      let restTime = new Date().valueOf() - timeStamp
      if (restTime > 1000 * 60 * 60 * 24) {
        Response.status(401).send({ message: statusList[401] });
      }
      if (permission[0] !== "all") {
        //通过权限校验
        User.Modal.findAll({
          where: {
            id: uid
          }
        }).then(res => {
          if (res && res.length > 0) {
            let permissionFlag = permission.some(item => item === res[0].permission);
            if (!permissionFlag) {
              Response.status(403).send({ message: statusList[403] });
            } else {
              //通过权限校验
              resolve('access')
            }
          } else {
            Response.status(300).send({ message: "抱歉，当前用户不存在" });
          }
        }).catch(err => {
          console.log(err)
          reject('err')
        });
      } else {
        resolve("success")
      }

    } else {
      Response.status(401).send({ message: statusList[401] });
    }
  })
}

function toJson(array, keys) {
  // array, keys 都传数组
  // 将数组内指定字段转换为josn
  array.forEach(arr => {
    keys.forEach(key => {
      arr[key] = JSON.parse(arr[key])
    });
  });
  return array;
}

function toString(array, keys) {
  // array, keys 都传数组
  // 将数组内指定字段转换为josn
  array.forEach(arr => {
    keys.forEach(key => {
      arr[key] = JSON.stringify(arr[key])
    });
  });
  return array;
}

function createOrderNumber() {
  // 创建唯一订单号
  let orderNumber = "";
  let nowStr = String(new Date().valueOf())
  orderNumber = nowStr.charAt(8) + nowStr.charAt(9) + nowStr.charAt(10) + nowStr
  return orderNumber;
}

export {
  checkPermission,
  toJson,
  toString,
  createOrderNumber,
}